package com.androidtv.pos.ui;

import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;

import com.androidhelper.module.common.base.BaseActivity;
import com.androidhelper.module.common.bean.BaseResponse;

import com.androidhelper.module.common.http.control.ProgressObserver;
import com.androidhelper.module.common.http.control.RxSchedulers;
import com.androidtv.pos.http.repo.MineRepo;
import com.androidhelper.module.common.utils.CheckUtils;
import com.androidhelper.module.common.utils.EditUtils;
import com.androidhelper.module.common.utils.ToastUtils;
import com.androidtv.pos.R;
import com.androidtv.pos.UIHelper;
import com.androidtv.pos.cache.SharePStore;
import com.androidtv.pos.utils.TextWatchHelp;
import com.androidtv.pos.modelbean.LoginData;

import androidx.annotation.Nullable;
import butterknife.BindView;
import io.reactivex.Observable;

public class PosLoginActivity  extends BaseActivity implements  View.OnClickListener,
        TextWatchHelp.TextChange, CompoundButton.OnCheckedChangeListener{

    @BindView(R.id.ll_clear_phone)
    ImageView ll_clear_phone;


    @BindView(R.id.cb_show_password_phone)
    CheckBox cb_show_password_phone;
    @BindView(R.id.cb_remember_account)
    CheckBox cb_remember_account;
    @BindView(R.id.cb_remember_password)
    CheckBox cb_remember_password;


    @BindView(R.id.btn_login)
    Button btn_login;



    @BindView(R.id.et_phone_number)
    EditText et_phone_number;
    @BindView(R.id.et_phone_password)
    EditText et_phone_password;







    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login_pos2;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
   boolean  cb1_isChecked=SharePStore.getAccountCBIsChecked();

       if(cb1_isChecked){
           cb_remember_account.setChecked(cb1_isChecked);
           String accountKey= SharePStore.getAccountKey();
           if(!isEmpty(accountKey)){
               et_phone_number.setText(accountKey);
               ll_clear_phone.setVisibility(View.VISIBLE);
           }
       }else{
           et_phone_number.clearComposingText();
           cb_remember_account.setChecked(cb1_isChecked);
           ll_clear_phone.setVisibility(View.GONE);

       }







    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {

    }

    @Override
    protected void setListener() {
         listenerForEditText();


        ll_clear_phone.setOnClickListener(this);
        cb_show_password_phone.setOnCheckedChangeListener(this);
        cb_remember_account.setOnCheckedChangeListener(this);
        cb_remember_password.setOnCheckedChangeListener(this);
        btn_login.setOnClickListener(this);




    }




    @Override
    protected void initStatusBar() {

    }

    @Override
    public void handleMessage(Message msg) {

    }

    @Override
    public void onClick(View view) {
      switch (view.getId()){
          case R.id.ll_clear_phone:
              et_phone_number.setText("");
              EditUtils.cursorFollow(et_phone_number);
              cb_remember_account.setChecked(false);

              break;

            case R.id.btn_login: //登陆
                //做网络请求
                doLogin();
                break;

        }
    }






    // 显示密码明文    记住账号  记住密码
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        switch (buttonView.getId()){
            case R.id.cb_show_password_phone: //显示密码
                 showPassword(isChecked);
                break;

            case R.id.cb_remember_account: //记住账号
                rememberAccount(isChecked);
                break;

            case R.id.cb_remember_password: //记住密码
                rememberPassword(isChecked);
                break;


        }

    }





    private void rememberAccount(boolean isChecked) {
        String  accountNumber=  et_phone_number.getText().toString().trim();

        if(isChecked){  //记住账号
            if(!isEmpty(accountNumber)){
                 ToastUtils.showTextInMiddle("记住账号");
                 SharePStore.setAccountKey(accountNumber);
                 SharePStore.setAccountCBIsChecked(isChecked);

             }else{
               //  ToastUtils.showTextInMiddle("请先输入账号");
                return;
             }

        }else{ //取消记住账号

            if(!isEmpty(accountNumber)){
                ToastUtils.showTextInMiddle("取消记住账号");
                SharePStore.removeAccountKey();
                SharePStore.setAccountCBIsChecked(isChecked);
            }else{
              //  ToastUtils.showTextInMiddle("请先输入账号");
                return;
            }
        }
    }


    //SharePStore.setPassword(loginData.getPassword());
    //!isEmpty(et_phone_number.getText().toString().trim(),et_phone_password.getText().toString().trim())

    private void rememberPassword(boolean isChecked) {
        if(isChecked){
              //ToastUtils.showTextInMiddle("记住密码");
              if(!isEmpty(et_phone_number.getText().toString().trim())){

              }else{

                  return;
              }

        }else{  //取消 记住密码

        }
    }


    private void showPassword(boolean isChecked) {
        if (isChecked) { //选中明文
            et_phone_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            et_phone_password.setEnabled(true);
            et_phone_password.requestFocus();
            EditUtils.cursorFollow(et_phone_password);
        }else {//未选中 暗纹
            et_phone_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            et_phone_password.setEnabled(true);
            et_phone_password.requestFocus();
            EditUtils.cursorFollow(et_phone_password);
        }

    }



    private void listenerForEditText() {
        et_phone_number.addTextChangedListener(new TextWatchHelp(this,R.id.et_phone_number));
        et_phone_password.addTextChangedListener(new TextWatchHelp(this, R.id.et_phone_password));
    }


    @Override
    public void afterTextChanged(Editable s, int id) {
        btn_login.setEnabled(checkIseEnable());

         switch (id){
             case R.id.et_phone_number:     //手机号码
                 String temp = s.toString().trim();
                 if(isEmpty(temp)){
                     ll_clear_phone.setVisibility(View.GONE);
                 }else{
                     ll_clear_phone.setVisibility(View.VISIBLE);
                 }

                 if(temp.length()==11){
                     et_phone_password.requestFocus();
                 }

                 if(temp.length()>11){
                     temp = temp.substring(0, 11);
                     //return;
                 }
                 if (!temp.equals(s.toString())) {
                     et_phone_number.setText(temp);
                 }

                 et_phone_number.setSelection(temp.length());

                 break;

             case R.id.et_phone_password:     //手机号码
                 String temp2 = s.toString().trim();
                 if(isEmpty(temp2)){
                     cb_show_password_phone.setVisibility(View.GONE);
                 }else{
                     cb_show_password_phone.setVisibility(View.VISIBLE);
                 }

                 break; //密码


         }



    }

    private boolean checkIseEnable() {
        if(!isEmpty(et_phone_number.getText().toString().trim(),et_phone_password.getText().toString().trim())){
            return true;
        }else{
            return false;
        }
    }


    private void doLogin() {


        String   mobilePhone = et_phone_number.getText().toString().trim();
        if (isEmpty(mobilePhone)) {
            ToastUtils.showErrorImage(mActivity.getResources().getString(R.string.phone_num_empty));
            return;
        }

        if(!CheckUtils.isMobile(mobilePhone)){
            ToastUtils.showTextInMiddle(mActivity.getResources().getString(R.string.error_phoneNumber ));
            return;
        }


        String  et_phone_passwordString = et_phone_password.getText().toString().trim();
        if (isEmpty(et_phone_passwordString)) {
            ToastUtils.showErrorImage(mActivity.getResources().getString(R.string.password_null_err));
            return;
        }
        if(!CheckUtils.checkPass(et_phone_passwordString )){return;}


        Observable<BaseResponse<LoginData>>     loginResponseObservable= MineRepo.getInstance().getService().postLoginData(mobilePhone,et_phone_passwordString);
        loginResponseObservable.compose(RxSchedulers.observableIO2Main())
                       .subscribe(new ProgressObserver<LoginData>(this,this.getString(R.string.loading)){


                           @Override
                           public void onSuccess(LoginData loginData) {
                                 //登录成功把用户名和密码 缓存sp
                             //  SharePStore.setAccountKey(loginData.getUsername());
                            //   SharePStore.setPassword(loginData.getPassword());



                                //登录成功
                               ToastUtils.showCorrectImage(getString(R.string.login_success));
                               UIHelper.jumptoMainActivity(PosLoginActivity.this);
                               finish();
                           }

                           @Override
                           public void onFailure(Throwable e, String errorMsg) {
                              //登录失败
                               ToastUtils.showErrorImage(errorMsg);
                           }
                       });

    }








    @Override    public boolean onTouchEvent(MotionEvent event) {
        if(null != this.getCurrentFocus()){
            /**             * 点击空白位置 隐藏软键盘             */
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            assert mInputMethodManager != null;
    return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super .onTouchEvent(event);
    }




}
